import Axios    from 'axios';
import $store   from '@/store';
import $router  from '@/router';
import $modal   from '@/utils/modal';
import $toast   from '@/utils/toast';
import $loading from '@/utils/loading';
import md5 from 'js-md5';
import { iosapp } from "@/utils";
const $http = Axios.create({
	baseURL: process.env.API_URL
});
// Before request
$http.interceptors.request.use(
    config => {
        if( window.location.href.indexOf("/member/invite/rule/") < 0 || window.sessionStorage.getItem('isapp') != '1'){
            $loading.open();
        }
        var token = window.localStorage.getItem('token');

        config.data.time = Date.parse(new Date()).toString().substr(0, 10);

        config.data.api_sign = md5(config.data.module + "sxtyg" + Date.parse(new Date()).toString().substr(0, 10));

        config.data.token = token ? token : '';
        
        return config;
    },
    error => {
        $loading.close();
        return Promise.reject(error);
    }
);
// After request
$http.interceptors.response.use(
    response => {
        $loading.close();
        var data = response.data;
        switch (data.code)
        {
			// Success   
			case 0:
				data.msg != '' && data.msg != 'OK' && data.msg != 'ok' && $toast(data.msg);
				return data;

			// Fail
			case 500:
                $modal.alert(data.msg).then(action => {
            		$router.back();
            	})
                return new Promise(() => {});

			// not logged
            case 305:
                $store.dispatch('logout');

                if(window.sessionStorage.getItem('isapp')  == '1')
                    return new Promise(() => { iosapp('ExperienceLoginAction') });

                $router.replace('/login?redirect=' + $router.currentRoute.fullPath);
				return new Promise(() => {});

            default:
                data.msg !== '' && $toast(data.msg);
				return new Promise(() => {});
        }
    },
    error => {
        $loading.close();
		// $toast('服务器异常')
        return Promise.reject(error);
    }
);

export default $http;